package com.kehutong.message.service;

import com.kehutong.common.util.Token;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.util.Enums;
import org.coraframework.util.Objects;
import com.kehutong.common.DoveClient;
import com.kehutong.common.enums.MessageBusinessEnum;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.common.errcode.Result;
import com.kehutong.message.entity.TemplateSetting;

import java.sql.Timestamp;

@WebService("/wechat/template/setting/service")
public class TemplateSettingService {

    static final Logger logger = LoggerFactory.getLogger(TemplateSettingService.class);

    @Inject
    private DoveClient doveClient;
    @Inject
    private JdbcSession jdbcSession;

    @Bean(newInstance = true, copy = true)
    @ReqMapping("/init")
    public Object init(TemplateSetting templateSetting, JSONObject jsonObject){

        MessageBusinessEnum businessEnum = Enums.getEnum(MessageBusinessEnum.class, jsonObject.getString("businessType"));
        TemplateType templateType = Enums.getEnum(TemplateType.class, jsonObject.getString("templateType"));
        templateSetting.setBusinessType(businessEnum);
        templateSetting.setTemplateType(templateType);

        TemplateSetting template = jdbcSession.findOne(TemplateSetting.class)
                                              .eq("templateType", templateSetting.getTemplateType())
                                              .eq("deleted", false)
                                              .exe();
        if (Objects.isNull(template)) {
            jdbcSession.insert(templateSetting);
        } else {
            templateSetting.setId(template.getId());
            jdbcSession.updateById(templateSetting);
        }
        syncGlobalConfig(templateSetting.getBusinessType(), templateSetting.getTemplateType(), templateSetting.getId());
        return Result.success(templateSetting);
    }

    public void syncGlobalConfig(MessageBusinessEnum businessEnum, TemplateType templateType, String id){
        try {
            doveClient.post("/crm/message/global/config/service/sync", http -> {
                http.addParam("businessType", businessEnum.getId());
                http.addParam("templateType", templateType.getId());
                http.addParam("wxchatTemplate", id);
            });
        } catch (Exception e){
            logger.error(e.getMessage(), e);
        }
    }

    @ReqMapping("/get")
    public Object get(String id){
        TemplateSetting item = Pool.get(TemplateSetting.class, id);
        return Result.success(item);
    }

    @ReqMapping("/find/msg/template")
    public Object getTemplateByType(JSONObject json){
        logger.info("[消息模板]根据消息类型获取消息模板,参数：{}",json);
        String templateType = json.getString("templateType");
        TemplateSetting template = jdbcSession.findOne(TemplateSetting.class)
                .eq("templateType", templateType)
                .eq("deleted", false)
                .exe();
        return Result.success(template);
    }
}
